package cn.gok.springbootlearning.service;

import cn.gok.springbootlearning.base.service.BaseService;
import cn.gok.springbootlearning.dao.StudentMapper;
import cn.gok.springbootlearning.dao.StudentRepository;
import cn.gok.springbootlearning.entity.Student;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * @ClassName StudentService
 * @Description TODO
 * @Author HP
 * @Date 14:13 2022/7/26
 * @Version 1.0
 **/
@Service
@Slf4j
public class StudentService extends BaseService<Student, StudentMapper> {

    @Autowired
    StudentMapper studentMapper;
    @Autowired
    StudentRepository studentRepository;


    @Cacheable(value = "user", key = "#id")
    public Student get(Integer id) {
        Student student = studentMapper.findById(id);
        log.info("[查询学生信息Service]：{}", student);
        return student;
    }

    /**
     * CachePut注解需要跟Cacheable注解的方法拥有相同的返回值，否则失效
     *
     * @param student
     * @return
     */
    @CachePut(value = "user", key = "#student.id")
    public Student saveCache(Student student) {
        if (student.getId() != null) {
            studentMapper.update(student);
        } else {
            studentMapper.save(student);
        }
        log.info("[保存学生信息Service]：{}", student);
        return studentMapper.findById(student.getId());
    }

    @CacheEvict(value = "user", key = "#id")
    public void deleteCache(Integer id) {
        studentMapper.delete(id);
        log.info("[删除学生信息Service]：{}", id);
    }

}
